/*
 * @Author: kenter.zheng
 * @Date: 2019-08-01 14:21:43
 * @Last Modified by: kenter.zheng
 * @Last Modified time: 2020-09-07 02:56:13
 */
import router from '../router'
import ElementUI from 'element-ui'
import { environment } from "../../models/environment"
import md5 from "js-md5";


export const signOut = () => {
  window.localStorage.clear()
  router.push('/login')
}

export const setItem = (key, value) => {
  if (!key) {
    return
  }
  if (typeof value !== 'string') {
    value = JSON.stringify(value)
  }
  window.localStorage.setItem(key, value)
}

export const getItem = (key) => {
  if (!key) {
    return
  }
  let result = window.localStorage.getItem(key);
  try {
    return JSON.parse(result)
  } catch (error) {
    return result
  }
  // return result != 'undefined' && JSON.parse(result)
}

export const removeItem = (key) => {
  if (!key) {
    return
  }
  window.localStorage.removeItem(key)
}

export const _waitTime = async (time) => {
  return new Promise((resolve, reject) => {
    setTimeout(function () {
      resolve();
    }, time);
  });
}

export function debounce(fn, delay) {
  let timer;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments) // 把参数传进去
    }, delay);
  }
}

/**
 * 深拷贝
 * @param {*} obj 
 * @returns 
 */
export const deepClone = (obj) => {
  let objClone = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === 'object') {
    for (let key in obj) {
      if (obj[key] && typeof obj[key] === 'object') {
        objClone[key] = deepClone(obj[key]);
      } else {
        objClone[key] = obj[key]
      }
    }
  }
  return objClone;
}

/**
 * 将数组转成对象
 * @param {*} list 数组列表
 * @param {*} key 转成对象key值数组用的字段
 * @param {*} value 转成对象value值数组用的字段
 * @returns 
 */
export const arrayToObj = (list, key, value) => {
  let obj = {};
  for (let index = 0; index < (list || []).length; index++) {
    const element = list[index];
    obj[element[key]] = element[value];
  }
  return obj;
}


